import Storage from '../lib/storage';
import UUID from '../lib/uuid';

const Cookies = new Storage('cookie');

/**
 * 数据埋点相关信息
 * @returns {String}
 */
 function getSrxUserInfo() {
    return Cookies.getItem('srxUserInfo') || `distinctId=${UUID()}`;
}

/**
 * 获取请求头相关参数
 * @returns {Object} 请求头header对象
 * @param {Record<string, string>} data
 */
 function getRequestHeaders(data) {
     let accessToken = Cookies.getItem('X-DT-accessToken') || ''; // TOKEN;
    //  let accessToken = '2594562c-e5dc-4b46-9dd8-2e90b92862d6'; // TOKEN;
    const headers = Object.assign(
        {
            'Content-Type': 'application/json',
            'Authorization': 'Basic c2FucmVuLXdhbmQtcGM6UjNOaHR2MUkyVVpsR1RmcTBv',
            'X-DT-clientId': 'sanren-teacher-pc',
            'X-DT-accessToken': accessToken,
            'X-DT-Passport': Cookies.getItem('passport') || '',
            'srxUserInfo': getSrxUserInfo()
        },
        data
    );
    return headers;
}

/**
 * 根据url解析domain，或是获取当前浏览器url的domain
 * @param {string=} url 解析url的domain
 * @returns 
 */
function getApiPrefixV2(url = '') {
    let domain = url || document.domain;
    let reg = /(?:www|www-dev\.)?([\w\-]*)*?(?:\.)?([\w\-]*)*?(?:\.)?([\w\-][\w\-]*?\.[\w\-\z]+)([\/|\?].*)?$/i;
    let arr = domain.match(reg);
    let str = '';
    
    if(arr && arr.length > 0) {
        if(arr[1]) {
            str = `${arr[1]}-api.${arr[2]}`;
        } else if(arr[2]) {
            if(/(-dev|-qa|-test)/.test(arr[2])) {
                str = arr[2].replace(/(-dev|-qa|-test)/, '-api$1').replace(/^-/, '');
            } else {
                str = `${arr[2]}-api`;
            }
        } else {
            str = 'api';
        }
        str += `.${arr[3]}`;
    }
    if(str) {
        return `${location.protocol}//${str}`;
    } else {
        throw new Error(`Get api host error: ${domain}`);
    }
}
export {
    getRequestHeaders,
    getApiPrefixV2
}
